package com.infinitus.activity.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.infinitus.activity.pojo.VO.ActivityConfigVO;
import com.infinitus.activity.pojo.VO.AwardsConfigVO;
import com.infinitus.activity.pojo.VO.ResponseVO;
import com.infinitus.activity.util.KeyGenerator;
import com.infinitus.activity.util.MapToObjectConvertionUtil;
import com.infinitus.activity.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: luzhenjie
 * @create: 2019/3/7
 * @desc:  对接接口
 */
@Controller
@RequestMapping(value = "/external")
public class ExternalController {

    private final static String CONFIG_TYPE_PRIZZE="prize";
    private final static String CONFIG_TYPE_BASE="base";
    private final static String CONFIGTYPE ="configtype";
    private final static String GROUPLIST = "groupList";
    private final static String GROUP_ID  = "group_id";

    @Value("${deploycolId}")
    private String deploycolId;

    @Value("${spring.redis.host}")
    private String redisHost;

    @Value("${spring.redis.port}")
    private String redisPort;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ActivityConfigVO activityConfig;

    //
    @ResponseBody
    @RequestMapping(value = "/getServerConfig",method = RequestMethod.GET)
    public ResponseEntity<?> getServerConfig(HttpServletRequest request, HttpServletResponse response) {
        Map<String,String> map = new HashMap<>();
        String serverConfig = "";
        try {
            serverConfig = stringRedisTemplate.opsForValue().get(KeyGenerator.getActivityConfig((deploycolId)));  //key待定
            map.put("serverConfig",serverConfig);
            map.put("deploycolId",deploycolId);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.ok(new ResponseVO<>().setContent(map));
    }


    /**
     * @Desc 重新加载活动配置 即重新读取Redis数据
     */
    @RequestMapping(value = "/reload",method = RequestMethod.GET)
    public ResponseEntity<?> reload() {
        String activityConfigJson= stringRedisTemplate.opsForValue().get(KeyGenerator.getActivityConfig(deploycolId));
        try {
            JSONObject activityConfigJsonObject = JSON.parseObject(activityConfigJson);
            JSONArray obj = (JSONArray) activityConfigJsonObject.get(GROUPLIST);
            ActivityConfigVO activityConfigVO =null;
            List<AwardsConfigVO> awardsConfigVOList = new ArrayList<AwardsConfigVO>();
            for (Object object : obj) {
                JSONObject group = (JSONObject) object;
                String groupId = (String) group.get(GROUP_ID);
                JSONArray jsonarray = (JSONArray) activityConfigJsonObject.get(groupId);
                Map<Object, Object> mapTemp = MapToObjectConvertionUtil.josnArrayToMap(jsonarray);
                if(null!=mapTemp.get(CONFIGTYPE)&&mapTemp.get(CONFIGTYPE).equals(CONFIG_TYPE_PRIZZE)) {
                    AwardsConfigVO awardsConfigVO = MapToObjectConvertionUtil.mapToObject(mapTemp, AwardsConfigVO.class);
                    awardsConfigVOList.add(awardsConfigVO);
                }else if(null!=mapTemp.get(CONFIGTYPE)&&mapTemp.get(CONFIGTYPE).equals(CONFIG_TYPE_BASE)) {
                    activityConfigVO = MapToObjectConvertionUtil.mapToObject(mapTemp, ActivityConfigVO.class);
                }
            }
            if(activityConfigVO!=null&&awardsConfigVOList.size()>0) {
                activityConfigVO.setAwardsConfigList(awardsConfigVOList);
            }

            //将奖品信息写入Redis中
            JSONArray jsonArray = new JSONArray();
            List<AwardsConfigVO> list = activityConfigVO.getAwardsConfigList();
            for (AwardsConfigVO awardsConfigVO : list) {
                jsonArray.add(awardsConfigVO);
            }
            stringRedisTemplate.opsForValue().set(KeyGenerator.getAwardsConfig(deploycolId),jsonArray.toJSONString());

            //重新设置config
            activityConfig.setRuleType(activityConfigVO.getRuleType());
            activityConfig.setLotteryTime(activityConfigVO.getLotteryTime());
            activityConfig.setActivityTime(activityConfigVO.getActivityTime());
        }catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.ok().build();
    }
}